package org.dromara.common.vcp.utils;


import org.dromara.common.vcp.domain.SzSecret;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 生成参数
 * @author cbx
 * @date 2020/7/3
 **/
public class GenReqParam {

    /**
     * 生成参数
     * @param specialParam 接口具体入参
     * @return
     */
    public static Map<String, Object> apiGen(Map<String, Object> specialParam, SzSecret szSecret) throws Exception{
        // 公共参数
        String appId = szSecret.getAppId();
        String version = szSecret.getVersion();
        String clientType = szSecret.getClientType();
        Long timestamp = System.currentTimeMillis();
        String appSecret = szSecret.getAppSecret();

        specialParam.put("appId", appId);
        specialParam.put("version", version);
        specialParam.put("clientType", clientType);
        specialParam.put("timestamp", timestamp);

        StringBuilder sb = new StringBuilder();
        Set<String> keySet = specialParam.keySet();
        for (String key : keySet) {
            Object value = specialParam.get(key);
            sb.append(key).append("=").append(value).append("&");
        }
        String result = sb.substring(0, sb.length() - 1);
        System.out.println("组装参数：" + result);
        String params = XXTea.encrypt(result,"UTF-8", ByteFormat.toHex(appSecret.getBytes()));
        System.out.println("XXTea加密参数：" + params);
        String signature = HmacSHATool.encodeHmacSHA256(appId + clientType + params + timestamp + version, appSecret);
        System.out.println("signature参数：" + signature);

        // 返回全部参数
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("appId", appId);
        resultMap.put("version", version);
        resultMap.put("clientType", clientType);
        resultMap.put("timestamp", timestamp);
        resultMap.put("signature", signature);
        resultMap.put("params", params);
        return resultMap;
    }
}
